package org.lgiavedoni.android.franq.event.listener;

import org.lgiavedoni.android.franq.core.Context;
import org.lgiavedoni.android.franq.core.envent.Event;
import org.lgiavedoni.android.franq.core.envent.listener.EventListener;
import org.lgiavedoni.android.franq.core.place.Place;
import org.lgiavedoni.android.franq.core.place.dao.PlaceDAO;
import org.lgiavedoni.android.franq.core.position.Position;
import org.lgiavedoni.android.franq.core.question.imp.NameOfPlaceQuestion;
import org.lgiavedoni.android.franq.event.CheckInEvent;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.phone.location.LocationService;
import org.lgiavedoni.android.franq.service.question.QuestionService;
import org.lgiavedoni.android.franq.util.googe.GeocodingUtil;
import org.lgiavedoni.android.franq.util.phone.wifi.WifiManager;

public class WelcomeEventListener extends EventListener {

	@Override
	public void exec(Event event) {
		Place place = ((CheckInEvent) event).getPlace();
		if (place.isUnknowName()) {
			// Ask for the name of the place
			QuestionService.inst.askNowAndWait(new NameOfPlaceQuestion(place), true);
		} else {
			CommunicationService.inst.sendDefaultTextMessage("Welcome to \"" + place.getName() + "\"");
		}
		// If the place don't have the GPS values we try to update it
		if (place.isUnknowLocation()) {
			Position position = LocationService.inst.getLocation();
			if (position != null && !position.isUnknowLocation()) {
				place.setLatitude(position.getLatitude());
				place.setLongitude(position.getLongitude());
				PlaceDAO.inst.update(place);
			} else {
				if (!place.isUnknowCell()) {
					GeocodingUtil.setLatLongFromCellId(place);
					PlaceDAO.inst.update(place);
				}
			}
		}
		// If the place don't have WIFI networks we try to update it
		if (place.isUnknowNetworks()) {
			place.setNetworks(((WifiManager) Context.getResource(WifiManager.class)).listWifiNetworksBSSID());
			PlaceDAO.inst.update(place);
		}
	}

	@Override
	public Class<CheckInEvent> getClassEvent() {
		return CheckInEvent.class;
	}

}
